package com.gzzyy.unionchain.ui.business.record

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSON
import com.gzzyy.unionchain.data.ObjectBox
import com.gzzyy.unionchain.data.bean.Block
import com.gzzyy.unionchain.data.bean.Block_
import com.gzzyy.unionchain.databinding.ActivityBlockListBinding
import com.gzzyy.unionchain.ui.base.BaseActivity
import com.gzzyy.unionchain.ui.business.record.adapter.BlockListAdapter
import kotlinx.coroutines.*

class BlockListActivity : BaseActivity() {

    private lateinit var binding: ActivityBlockListBinding
    private lateinit var blockAdapter: BlockListAdapter
    private var queryJob: Job? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBlockListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbar.setNavigationOnClickListener { finish() }
        binding.blockListRv.layoutManager = LinearLayoutManager(baseContext)
        blockAdapter =
            BlockListAdapter()
        binding.blockListRv.adapter = blockAdapter
        blockAdapter.setOnItemClickListener { adapter, _, pos ->
            val block = adapter.getItem(pos) as Block
            startActivity(
                BlockDetailActivity::class.java,
                Pair(BlockDetailActivity.BlockJson, JSON.toJSONString(block))
            )
        }
        setQueryJob()
    }


    private fun setQueryJob() {
        queryJob = GlobalScope.launch {
            val blockBox = ObjectBox.getBlockBox()
            val blockList = blockBox.query().orderDesc(Block_.height).build().find()
            withContext(Dispatchers.Main) {
                blockAdapter.setNewData(blockList)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        queryJob?.cancel()
    }
}